package com.bootadmin.core.web;

import com.bootadmin.core.utils.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author kongzm
 * @description: 拦截器
 * @date 2022/1/15 20:25
 */
@Component
public class WebInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println(request.getRequestURI());
        String token = request.getHeader("token");// 从 http 请求头中取出 toke
        if (StringUtils.isEmpty(token)) {
            token = request.getParameter("token");
        }
        if (StringUtils.isEmpty(token)) {
            setResponse(response, SystemConstant.LOGIN_FAILURE_CODE, "缺少token");
            return false;
        }

        // 校验token
        // JwtUtils.verifyJWT(token);

        return true;
    }

    @Override
    public void postHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, java.lang.Object handler, org.springframework.web.servlet.ModelAndView modelAndView) throws java.lang.Exception {
    }
    
    @Override
    public void afterCompletion(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, java.lang.Object handler, java.lang.Exception ex) throws java.lang.Exception {
    }    

    private void setResponse(HttpServletResponse response, Integer code, String msg) throws IOException {
        ResultJson res = ResultJson.error(code, "操作失败", msg);
        response.setStatus(200);
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.getWriter().write(StringUtils.toJsonString(res));
    }
}
